/**
 * @file writev.c
 * @author lyke (1556553295@qq.com)
 * @brief 向量IO writev() 示例实例代码
 * @version 0.1
 * @date 2023-01-30
 *
 * @copyright Copyright (c) 2023
 *
 */

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

int main(int argc, char const *argv[]) {
  struct iovec iov[4];
  size_t write_len;
  int fd;

  char *buf[] = {"11111\n", "22222\n", "33333\n", "44444\n"};
  fd = open("recoder.txt", O_WRONLY | O_CREAT | O_TRUNC);
  if (-1 == fd) {
    perror("open");
    return 1;
  }

  for (size_t i = 0; i < 4; i++) {
    iov[i].iov_base = buf[i];
    iov[i].iov_len = strlen(buf[i]) + 1;
  }

  write_len = writev(fd, iov, 4);
  if (-1 == write_len) {
    perror("writev");
    return 1;
  }
  printf("write %zu bytes.\n", write_len);

  if (close(fd)) {
    perror("close");
  }

  return 0;
}
